import axios from 'axios';

const getBaseURL = () => {
  if (import.meta.env.DEV) {
    return 'http://localhost:8001';
  } else {
    return window.location.origin;
  }
};

const api = axios.create({
  baseURL: getBaseURL(),
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

api.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
}, error => {
  return Promise.reject(error);
});

api.interceptors.response.use(response => {
  if (response.data && response.data.code !== undefined) {
    if (response.data.code === 0 || response.data.code === 200) {
      return response.data.data;
    } else {
      return Promise.reject(response.data);
    }
  } else {
    return response.data;
  }
}, error => {
  console.error('API Error:', error);
  if (error.response?.status === 401) {
    window.location.href = '/login';
  }
  const errorData = error.response?.data || {
    code: -1,
    message: 'Network Error'
  };
  return Promise.reject(errorData);
});

export const http = {
  get: (endpoint, params) => api.get(endpoint, { params }),
  post: (endpoint, data) => api.post(endpoint, data),
  put: (endpoint, data) => api.put(endpoint, data),
  patch: (endpoint, data) => api.patch(endpoint, data),
  delete: (endpoint) => api.delete(endpoint),
  upload: (endpoint, file) => {
    const formData = new FormData();
    formData.append('file', file);
    return api.post(endpoint, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }
};

export { getBaseURL };